package com.hzzh.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hzzh.util.ConnectionFactory;
import com.hzzh.vo.Department;

public class DepartmentDAO {

	private Connection conn;
	private PreparedStatement ps;
	private ResultSet  rs;

	// 查询所有部门信息，返回到集合中
	public ArrayList<Department> selectAllDepartmentDAO() {
		conn = ConnectionFactory.getConnection();
		ArrayList<Department> departmentsList = new ArrayList<Department>();
		try {
			String sql = "select * from department";
			ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			Department department;
			while (rs.next()) {
				department = new Department();
				department.setDepartmentid(rs.getString("departmentid"));
				department.setDepartmentname(rs.getString("departmentname"));
				departmentsList.add(department);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ConnectionFactory.closeConnection(rs, ps, conn);
		}
		return departmentsList;
	}

	// 向表department中插入记录
	public void insert(String departmentname) {
		conn = ConnectionFactory.getConnection();
		String sql = "insert into department values(dept_id_seq.nextval,?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, departmentname);
			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ConnectionFactory.closeConnection(rs, ps, conn);
		}
	}

	// 根据id删除一个部门
	public void delete(int departmentid) {
		conn = ConnectionFactory.getConnection();
		String sql = "delete from department where departmentid=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, departmentid);
			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ConnectionFactory.closeConnection(rs, ps, conn);
		}
	}

}
